package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFavourMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetMealDishMapper setMealDishMapper;
    @Autowired
    DishFavourMapper dishFavourMapper;

    @Override
    public List<Dish> GetDishesByCategoryId(Long id) {
       return dishMapper.GetDishesByCategoryId(id);
    }

    @Override
    public void save(Dish dish) {



         dishMapper.insert(dish);
    }

    @Override
    public PageResult SelectBypage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //PageResult
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dish);
        Page<Dish> page = dishMapper.select(dish);
        PageResult pageResult = new PageResult(page.getTotal(), page);
        return pageResult;
    }

    @Override
    public void StartOrclose(Integer status,Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    @Override
    public  void Delete(List<Long> list) {
        //有在售中的餐品不能删除
         List<String> list1 =  dishMapper.SelectById(list);
         for(int i = 0; i < list1.size(); i++){
             if(list1.get(i).equals("1")){

                throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
             }

         }
         //若套餐中存在该菜品则不能删除
         List<Long> Idlist = setMealDishMapper.GetSetMealIdsByDishId(list);
         if(Idlist != null && Idlist.size() > 0){
             new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
         }
         //删除菜品表中的菜品
         dishMapper.Delete(list);
         //删除口味表中关联的菜品


    }

    @Override
    public DishVO getById(Long id) {
        Dish dish =  dishMapper.GetById(id);
        List<DishFlavor> dishFlavorList = dishFavourMapper.GetByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    @Override
    public void Update(DishDTO dishDTO) {
         Dish dish = new Dish();
         BeanUtils.copyProperties(dishDTO,dish);
         dishMapper.update(dish);

    }
}
